package user_controller

import (
	"fmt"
	"gin-project/database"
	"gin-project/entity"
	"gin-project/util"
	"net/http"

	"github.com/gin-gonic/gin"
)

// 获取用户列表
func GetUserList(c *gin.Context) {
	var userList []entity.User
	sqlStr := "select * from tb_user"
	result := database.DB.Raw(sqlStr).Scan(&userList)
	if result.Error != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    500,
			"message": "获取用户列表失败",
			"error":   result.Error.Error(),
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "获取用户列表成功",
		"data":    userList,
	})
}

// 添加用户
func AddUser(c *gin.Context) {
	var user entity.User
	err := c.ShouldBindJSON(&user)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    500,
			"message": "参数传递错误",
			"error":   err.Error(),
		})
		return
	}
	uuid := util.GetUUID()
	user.Id = uuid
	currentTime := util.GetCurrentTime()
	user.CreateTime = currentTime
	user.UpdateTime = currentTime
	sqlStr := fmt.Sprintf("insert into tb_user(id,username,password,email,create_time,update_time) values('%s','%s','%s','%s','%s','%s')", user.Id, user.Username, user.Password, user.Email, user.CreateTime, user.UpdateTime)
	result := database.DB.Exec(sqlStr)
	if result.Error != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    500,
			"message": "添加失败",
			"error":   result.Error.Error(),
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "添加成功",
	})
}

// 根据用户名获取用户信息
func GetUserByUsername(c *gin.Context) {
	var user entity.User
	err := c.ShouldBindJSON(&user)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    500,
			"message": "参数传递错误",
			"error":   err.Error(),
		})
		return
	}
	sqlStr := fmt.Sprintf("select * from tb_user where username='%s'", user.Username)
	var userList []entity.User
	result := database.DB.Raw(sqlStr).Scan(&userList)
	if result.Error != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    500,
			"message": "获取用户信息失败",
			"error":   result.Error.Error(),
		})
	}
	if len(userList) == 0 {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    500,
			"message": "用户不存在",
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "获取用户信息成功",
		"data":    userList,
	})
}
